/*
 * acm1051.c
 *
 *  Created on: 20 Mar 2010
 *      Author: xuxu
 */
#include<stdio.h>
int main()
{
	int now[20][20] =
	{ 0 };
	int yesterday[22][22] =
	{ 0 };
	int state[16];
	int day;
	int n, i, j;
	int tmp;
	scanf("%d", &n);
	while (n--)
	{
		scanf("%d", &day);
		for (i = 0; i < 16; i++)
		{
			scanf("%d", &state[i]);
		}
		for (i = 0; i < 20; i++)
		{
			for (j = 0; j < 20; j++)
			{
				scanf("%d", &now[i][j]);
				yesterday[i + 1][j + 1] = now[i][j];
			}
		}
		while (day--)
		{
			for (i = 0; i < 20; i++)
			{
				for (j = 0; j < 20; j++)
				{
					tmp = yesterday[i + 1][j + 1] + yesterday[i][j + 1]
							+ yesterday[i + 1][j] + yesterday[i + 2][j + 1]
							+ yesterday[i + 1][j + 2];
					now[i][j] = state[tmp] + now[i][j];
					if (now[i][j] < 0)
						now[i][j] = 0;
					else if (now[i][j] > 3)
						now[i][j] = 3;
				}
			}
			for (i = 1; i < 21; i++)
			{
				for (j = 1; j < 21; j++)
				{
					yesterday[i][j] = now[i - 1][j - 1];
				}
			}
		}
		for (i = 0; i < 20; i++)
		{
			for (j = 0; j < 20; j++)
			{
				if (3 == now[i][j])
					printf("#");
				else if (2 == now[i][j])
					printf("X");
				else if (1 == now[i][j])
					printf("!");
				else
					printf(".");
			}
			printf("\n");
		}
		if (n)
			printf("\n");

	}
	return 0;
}
